<template>
  <view class="container">
    <!-- 顶部筛选区域（上下排列） -->
    <view class="filter-area">
      <!-- 第一行：项目和站点选择 -->
      <!-- 第一行：项目和站点选择 -->
      <view class="filter-row">
        <!-- 项目选择 -->
        <view class="filter-item">
          <text class="filter-label">项目：</text>
          <picker
            mode="selector"
            :range="projectList"
            range-key="projectName"
            @change="onProjectChange"
          >
            <view class="picker">
              {{ selectedProjectName || "请选择项目" }}
            </view>
          </picker>
        </view>

        <!-- 站点选择 -->
        <view class="filter-item">
          <text class="filter-label">站点：</text>
          <picker
            mode="selector"
            :range="siteList"
            range-key="siteName"
            @change="onSiteChange"
            :disabled="!selectedProjectId"
          >
            <view class="picker">
              {{ selectedSiteName || "请选择站点" }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 第二行：语音输入组件 -->
      <!-- <view class="voice-row">
        <BrowserVoiceInput 
          placeholder="点击开始语音输入，说出项目名称..."
          language="zh-CN"
          :continuous="false"
          :interim-results="true"
          @transcript="handleVoiceTranscript"
          @start="onVoiceStart"
          @end="onVoiceEnd"
          @error="onVoiceError"
        />
      </view> -->
      <!-- 现代化搜索组件 -->
      <view class="modern-search-container">
        <view class="search-wrapper">
          <input
            class="modern-search-input"
            placeholder="搜索项目名称..."
            v-model="searchText"
            @keypress.enter="onSearch"
          />
          <button class="modern-search-btn" @tap="onSearch">
            <text class="search-icon">🔍</text>
            <text class="search-text">搜索</text>
          </button>
        </view>
      </view>

      <!-- 表格类型切换标签栏 -->
      <view class="tab-bar" v-if="selectedProjectId">
        <view
          v-for="tab in tabs"
          :key="tab.key"
          class="tab-item"
          :class="{ 'active-tab': selectedTab === tab.key }"
          @tap="selectTab(tab.key)"
        >
          <text>{{ tab.label }}</text>
        </view>
      </view>
    </view>

    <!-- 未选项目/站点时的提示 -->
    <view v-if="!selectedProjectId" class="empty-message">
      请先选择"项目"
    </view>
    <view v-else-if="!selectedSiteTaskId" class="empty-message">
      请先选择"站点"
    </view>

    <!-- 暂存修改提示 -->
    <view v-if="pendingChanges.length > 0" class="pending-changes-tip">
      <text class="tip-icon">📝</text>
      <text class="tip-text"
        >当前有 {{ pendingChanges.length }} 条修改待提交</text
      >
    </view>

    <!-- 用量清单 -->
    <UsageList
      v-if="selectedTab === 'usage' && selectedProjectId && selectedSiteTaskId"
      :list="usageList"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'usage', index)
      "
    />

    <!-- 机器使用费 -->
    <MachineUsage
      v-if="
        selectedTab === 'machine' && selectedProjectId && selectedSiteTaskId
      "
      :list="machineUsageList"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'machine', index)
      "
    />

    <!-- 仪器使用费 -->
    <InstrumentUsage
      v-if="
        selectedTab === 'instrument' && selectedProjectId && selectedSiteTaskId
      "
      :list="instrumentUsageList"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'instrument', index)
      "
    />

    <!-- 甲供材料 -->
    <JGMaterials
      v-if="selectedTab === 'jg' && selectedProjectId && selectedSiteTaskId"
      :jgList="supplierAMaterials"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'jg', index)
      "
    />

    <!-- 乙供材料 -->
    <YGMaterials
      v-if="selectedTab === 'yg' && selectedProjectId && selectedSiteTaskId"
      :ygList="supplierBMaterials"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'yg', index)
      "
    />

    <!-- 其他材料 -->
    <OtherMaterials
      v-if="selectedTab === 'other' && selectedProjectId && selectedSiteTaskId"
      :list="otherMaterialsList"
      :pendingChanges="pendingChanges"
      :modifiedRecords="modifiedRecords"
      @row-double-click="
        (item, _, index) => handleRowDoubleClick(item, 'other', index)
      "
    />

    <!-- 底部按钮区域 -->
    <view class="bottom-buttons">
      <!-- 历史上报 -->
      <view class="action-btn history-btn" @tap="onHistoryReport">
        <view class="btn-text">清除所有暂存</view>
      </view>
      <!-- 提交所有更改 -->
      <view class="action-btn report-btn" @tap="openReportModal">
        <view class="btn-text">
          提交所有更改
          <text v-if="pendingChanges.length > 0" class="badge">{{
            pendingChanges.length
          }}</text>
        </view>
      </view>
    </view>

    <view
      v-if="isReportModalOpen"
      class="modal-mask"
      @tap="handleReportMaskClick"
    >
      <view class="modal-container" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">问题上报</text>
          <!-- 关闭按钮 -->
          <view class="modal-close" @tap="closeReportModal">
            <text class="close-text">×</text>
          </view>
        </view>
        <view class="modal-body">
          <CustomForm
            :projectInfo="currentProjectInfo"
            :accPerson="userInfo.username"
            @formSubmit="handleFormSubmit"
          />
        </view>
      </view>
    </view>

    <!-- 历史上报模态框（抽成组件） -->
    <HistoryModal
      :visible="isHistoryModalOpen"
      :projectId="selectedProjectId"
      :siteId="selectedSiteTaskId"
      @close="closeHistoryModal"
    />

    <!-- 记录更新模态框 -->
    <RecordUpdateModal
      ref="recordUpdateModalRef"
      :visible="isUpdateModalVisible"
      :recordData="currentRecord"
      @close="closeUpdateModal"
      @submit="handleUpdateSubmit"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import CustomForm from "@/components/CustomForm.vue";
import BrowserVoiceInput from "@/components/BrowserVoiceInput.vue";

// 接收父组件传递的task_id
const props = defineProps({
  taskId: {
    type: [String, Number],
    default: null,
  },
});

// 已有的子组件
import UsageList from "@/components/UsageList.vue";
import JGMaterials from "@/components/JGMaterials.vue";
import YGMaterials from "@/components/YGMaterials.vue";
// 新增的子组件
import MachineUsage from "@/components/MachineUsage.vue";
import InstrumentUsage from "@/components/InstrumentUsage.vue";
import OtherMaterials from "@/components/OtherMaterials.vue";

// 记录更新模态框
import RecordUpdateModal from "@/components/RecordUpdateModal.vue";

const fullProjectData = ref([]);
const projectList = ref([]);
const siteList = ref([]);

const selectedProjectId = ref(null);
const selectedProjectName = ref("");
const selectedSiteTaskId = ref(null);
const selectedSiteName = ref("");

// 原有数据列表
const usageList = ref([]);
const supplierAMaterials = ref([]);
const supplierBMaterials = ref([]);
// 新增数据列表
const machineUsageList = ref([]);
const instrumentUsageList = ref([]);
const otherMaterialsList = ref([]);

// 当前选中的"表格类型"标签
const selectedTab = ref("usage");
const tabs = [
  { key: "usage", label: "用量清单" },
  { key: "machine", label: "机器使用" },
  { key: "instrument", label: "仪器使用" },
  { key: "jg", label: "甲供材料" },
  { key: "yg", label: "乙供材料" },
  { key: "other", label: "其他材料" },
];

const ui = uni.getStorageSync("userInfo");
const userInfo = ref({
  username: ui.name,
});

const isReportModalOpen = ref(false);
const isHistoryModalOpen = ref(false);
// 记录更新模态框相关状态
const isUpdateModalVisible = ref(false);
const recordUpdateModalRef = ref(null);
const currentRecord = ref({
  id: null,
  currentValue: "",
  type: "",
});

// 跟踪已修改的记录ID
const modifiedRecords = ref([]);

// 暂存的修改记录
const pendingChanges = ref([]);

// 当前位置信息
const currentLocation = ref({
  lat: null,
  lon: null,
});

// 搜索文本
const searchText = ref("");

onMounted(() => {
  console.log("=== classic.vue onMounted调试 ===");
  console.log("props对象:", props);
  console.log("props.taskId:", props.taskId, typeof props.taskId);

  fetchProjectAndSiteData();
  getCurrentLocation();
  // 清空 window.recordUpdateStorage
  window.recordUpdateStorage = {};
  if (props.taskId) {
    getRecordFTM();
  }
});

onUnmounted(() => {
  // 清理资源
});

// 重置所有数据
function resetAllData() {
  usageList.value = [];
  machineUsageList.value = [];
  instrumentUsageList.value = [];
  supplierAMaterials.value = [];
  supplierBMaterials.value = [];
  otherMaterialsList.value = [];
  selectedTab.value = "usage";
}

// 重置站点数据
function resetSiteData() {
  selectedSiteTaskId.value = null;
  selectedSiteName.value = "";
  siteList.value = [];
  resetAllData();
}

// 更新站点列表
function updateSiteList() {
  if (selectedProjectId.value) {
    siteList.value = fullProjectData.value
      .filter((item) => item.misCode === selectedProjectId.value)
      .map((item) => ({
        subtaskId: item.subtaskId,
        siteName: item.siteName,
      }));
  }
}

// 加载所有标签页数据
function loadAllTabData() {
  if (selectedSiteTaskId.value && selectedProjectId.value) {
    fetchUsageList(selectedProjectId.value, selectedSiteTaskId.value);
    fetchMachineUsage(selectedProjectId.value, selectedSiteTaskId.value);
    fetchInstrumentUsage(selectedProjectId.value, selectedSiteTaskId.value);
    fetchSupplierAMaterials(selectedProjectId.value, selectedSiteTaskId.value);
    fetchSupplierBMaterials(selectedProjectId.value, selectedSiteTaskId.value);
    fetchOtherMaterials(selectedProjectId.value, selectedSiteTaskId.value);
  }
}

// 处理搜索按钮点击
const onSearch = () => {
  if (searchText.value.trim()) {
    analyzeVoiceIntent(searchText.value.trim());
  } else {
    uni.showToast({
      title: "请输入查询内容",
      icon: "none",
    });
  }
};

// 处理语音转录结果
// function handleVoiceTranscript(voiceText) {
//   console.log("语音识别结果:", voiceText);
//   analyzeVoiceIntent(voiceText);
// }

// 简单字符串匹配作为备选方案
// const findProjectBySimpleMatch = (voiceText) => {
//   // console.log("开始简单匹配，语音内容：", voiceText);

//   // 清理语音文本，移除常见的无关词汇
//   const cleanText = voiceText.replace(/[选择|我要|项目|工程|的|了|吧|呢|啊]/g, '').trim();
//   // console.log("清理后的文本：", cleanText);

//   // 遍历项目列表进行匹配
//   for (const project of projectList.value) {
//     const projectName = project.projectName;
//     // console.log("检查项目：", projectName);

//     // 1. 完全匹配
//     if (cleanText === projectName) {
//       // console.log("完全匹配成功");
//       return project;
//     }

//     // 2. 包含匹配（语音文本包含项目名）
//     if (cleanText.includes(projectName) || projectName.includes(cleanText)) {
//       // console.log("包含匹配成功");
//       return project;
//     }

//     // 3. 部分匹配（项目名的关键词）
//     const keywords = projectName.split(/[、，,\s]+/);
//     for (const keyword of keywords) {
//       if (keyword.length >= 2 && (cleanText.includes(keyword) || keyword.includes(cleanText))) {
//         // console.log("关键词匹配成功：", keyword);
//         return project;
//       }
//     }
//   }

//   // console.log("简单匹配未找到项目");
//   return null;
// };

// 使用LLM分析语音意图并匹配项目
const analyzeVoiceIntent = (voiceText) => {
  uni.showLoading({
    title: "分析意图中...",
    mask: true,
  });

  // 构建项目-站点组合列表字符串
  const projectSiteList = [];
  fullProjectData.value.forEach((item, index) => {
    projectSiteList.push({
      index: index,
      projectName: item.projectName,
      siteName: item.siteName,
      misCode: item.misCode,
      subtaskId: item.subtaskId,
    });
  });

  const projectListStr = projectSiteList
    .map((item, index) => `${index}：${item.projectName}-${item.siteName}`)
    .join("\n");

  // console.log(projectListStr);

  const prompt = `用户输入了："${voiceText}"
可选的项目列表：
${projectListStr}
请分析用户输入的内容，找出用户想要选择的项目。请进行模糊匹配，考虑以下情况：
1. 用户可能只输入了项目名称的一部分
2. 用户可能输入了"选择XX项目"、"我要XX"、"XX工程"等表达方式

如果能够匹配到项目，请返回项目的索引号（从0开始）。
如果完全无法匹配，请返回-1。

只返回数字，不要返回其他内容。`;

  uni.request({
    url: "http://192.168.8.30:7077/v1/chat/completions",
    method: "POST",
    header: {
      // 'Authorization': 'Bearer sk-znumummvzniscpunpzxuwixyexuysfkevdkaprhupfhdmtqo',
      "Content-Type": "application/json",
    },
    data: {
      model: "Qwen-72B",
      messages: [
        {
          role: "user",
          content: prompt,
        },
      ],

      temperature: 0.1,
      stream: false,
    },
    success: (res) => {
      uni.hideLoading();
      // console.log("LLM分析结果：", res.data);
      // console.log("用户语音内容：", voiceText);
      // console.log("项目列表：", projectList.value);
      uni.showToast({
        title: res,
        icon: "none",
      })
      if (
        res.statusCode === 200 &&
        res.data.choices &&
        res.data.choices[0] &&
        res.data.choices[0].message
      ) {
        const result = res.data.choices[0].message.content.trim();
        // console.log("LLM返回结果：", result);
        const projectIndex = parseInt(result);

        if (projectIndex >= 0 && projectIndex < projectSiteList.length) {
          // 找到匹配的项目-站点组合，自动选择
          const selectedItem = projectSiteList[projectIndex];
          // console.log("匹配到的项目-站点组合：", selectedItem);

          selectedProjectId.value = selectedItem.misCode;
          selectedProjectName.value = selectedItem.projectName;
          selectedSiteTaskId.value = selectedItem.subtaskId;
          selectedSiteName.value = selectedItem.siteName;

          // 重置数据列表
          usageList.value = [];
          machineUsageList.value = [];
          instrumentUsageList.value = [];
          supplierAMaterials.value = [];
          supplierBMaterials.value = [];
          otherMaterialsList.value = [];
          selectedTab.value = "usage";

          // 更新站点列表
          siteList.value = fullProjectData.value
            .filter((item) => item.misCode === selectedProjectId.value)
            .map((item) => ({
              subtaskId: item.subtaskId,
              siteName: item.siteName,
            }));

          // 直接加载选中项目和站点的数据
          if (selectedSiteTaskId.value && selectedProjectId.value) {
            fetchUsageList(selectedProjectId.value, selectedSiteTaskId.value);
            fetchMachineUsage(
              selectedProjectId.value,
              selectedSiteTaskId.value
            );
            fetchInstrumentUsage(
              selectedProjectId.value,
              selectedSiteTaskId.value
            );
            fetchSupplierAMaterials(
              selectedProjectId.value,
              selectedSiteTaskId.value
            );
            fetchSupplierBMaterials(
              selectedProjectId.value,
              selectedSiteTaskId.value
            );
            fetchOtherMaterials(
              selectedProjectId.value,
              selectedSiteTaskId.value
            );
          }

          uni.showToast({
            title: `已选择：${selectedItem.projectName}-${selectedItem.siteName}`,
            icon: "success",
          });
        } else {
          // 如果LLM返回-1，尝试简单的字符串匹配作为备选方案
          // console.log("LLM未找到匹配，尝试简单匹配");
          const matchedProject = findProjectBySimpleMatch(voiceText);
          if (matchedProject) {
            // console.log("简单匹配找到项目：", matchedProject);

            selectedProjectId.value = matchedProject.misCode;
            selectedProjectName.value = matchedProject.projectName;

            // 重置站点数据
            selectedSiteTaskId.value = null;
            selectedSiteName.value = "";
            siteList.value = [];
            usageList.value = [];
            machineUsageList.value = [];
            instrumentUsageList.value = [];
            supplierAMaterials.value = [];
            supplierBMaterials.value = [];
            otherMaterialsList.value = [];
            selectedTab.value = "usage";

            // 加载站点数据
            if (selectedProjectId.value) {
              siteList.value = fullProjectData.value
                .filter((item) => item.misCode === selectedProjectId.value)
                .map((item) => ({
                  subtaskId: item.subtaskId,
                  siteName: item.siteName,
                }));
            }

            uni.showToast({
              title: `已选择项目：${matchedProject.projectName}`,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: `未找到匹配的项目。语音内容："${voiceText}"`,
              icon: "none",
              duration: 3000,
            });
          }
        }
      } else {
        uni.showToast({
          title: "语音分析失败，请重新尝试",
          icon: "none",
        });
      }
    },
    fail: (error) => {
      uni.hideLoading();
      // console.error("LLM分析错误：", error);
      uni.showToast({
        title: error,
        icon: "none",
      });
    },
  });
};

// 获取当前位置
function getCurrentLocation() {
  uni.getLocation({
    type: "wgs84", // 返回可以用于uni.openLocation的经纬度
    success: (res) => {
      currentLocation.value = {
        lat: res.latitude,
        lon: res.longitude,
      };
      // console.log('获取位置成功:', currentLocation.value);
    },
    fail: (err) => {
      console.error("获取位置失败:", err);
      // 如果获取位置失败，可以设置默认值或提示用户
      uni.showToast({
        title: "获取位置失败，请检查定位权限",
        icon: "none",
      });
    },
  });
}

// 获取未确认的修改记录
async function getRecordFTM() {
  console.log("=== getRecordFTM 开始执行 ===");
  console.log("props.taskId:", props.taskId, typeof props.taskId);

  if (!props.taskId) {
    console.log("没有taskId，跳过获取暂存记录");
    return;
  }

  try {
    uni.showLoading({
      title: "加载暂存记录...",
      mask: true,
    });

    const res = await new Promise((resolve, reject) => {
      console.log("发送GetRecordFTM请求，参数:", { record_id: props.taskId });
      uni.request({
        url: "./api/GetRecordFTM",
        method: "POST",
        header: {
          Authorization: `Bearer ${ui.token}`,
          "Content-Type": "application/json",
        },
        data: {
          record_id: props.taskId,
        },
        timeout: 15000, // 15秒超时
        success: (response) => {
          console.log("GetRecordFTM请求成功:", response);
          resolve(response);
        },
        fail: (error) => {
          console.error("GetRecordFTM请求失败:", error);
          reject(error);
        },
      });
    });

    uni.hideLoading();

    if (res.statusCode === 200) {
      // 检查返回数据格式，支持多种后端返回格式
      let recordsData = [];

      if (Array.isArray(res.data)) {
        recordsData = res.data;
      } else if (res.data && Array.isArray(res.data.data)) {
        recordsData = res.data.data;
      } else if (res.data && res.data.success && Array.isArray(res.data.data)) {
        recordsData = res.data.data;
      }

      if (recordsData.length > 0) {
        console.log("获取到暂存记录:", recordsData);

        // 处理返回的数据，优化图片数据处理逻辑
        const processedData = recordsData.map((item) => {
          console.log(
            "处理记录:",
            item.MIS_id,
            "图片数量:",
            item.photo_path?.length || 0
          );

          return {
            ...item,
            photo_path: processPhotoPathData(item.photo_path || []),
          };
        });

        console.log("GetRecordFTM返回的原始数据:", res.data);

        // 将处理后的数据恢复到RecordUpdateModal组件的全局存储中
        loadPreviousRecords(processedData);

        console.log("暂存记录已恢复到本地存储");

        // 显示成功提示
        uni.showToast({
          title: `已恢复${processedData.length}条暂存记录`,
          icon: "success",
          duration: 2000,
        });

        // 统计图片总数
        const totalImages = processedData.reduce(
          (sum, item) => sum + (item.photo_path?.length || 0),
          0
        );
        if (totalImages > 0) {
          console.log(`总共恢复了${totalImages}张图片`);
        }
      } else {
        console.log("没有找到暂存记录");
      }
    } else {
      console.error("GetRecordFTM接口返回错误状态:", res.statusCode, res.data);
      uni.showToast({
        title: "获取暂存记录失败",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("获取暂存记录失败:", error);

    // 根据错误类型显示不同提示
    if (error.errMsg) {
      if (error.errMsg.includes("timeout")) {
        uni.showToast({
          title: "请求超时，请检查网络",
          icon: "none",
          duration: 3000,
        });
      } else if (error.errMsg.includes("fail")) {
        uni.showToast({
          title: "网络连接失败",
          icon: "none",
          duration: 3000,
        });
      } else {
        console.log("其他网络错误，不显示提示");
      }
    }
  }
}

// 将ArrayBuffer转换为base64字符串
function arrayBufferToBase64(buffer) {
  let binary = "";
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

// 处理图片路径数据，支持多种后端返回格式
function processPhotoPathData(photoPathArray) {
  if (!Array.isArray(photoPathArray)) {
    console.log("图片数据不是数组格式:", photoPathArray);
    return [];
  }

  return photoPathArray
    .map((photoData, index) => {
      console.log(
        `处理第${index + 1}张图片，数据类型:`,
        typeof photoData,
        photoData
      );

      // 检查图片数据格式
      if (!photoData) {
        console.warn(`第${index + 1}张图片数据为空`);
        return null;
      }

      try {
        // 情况1: 后端返回的是对象格式 {id: 'uuid', data: 'base64数据'}
        if (typeof photoData === "object" && photoData.id && photoData.data) {
          console.log(`第${index + 1}张图片是对象格式，ID:`, photoData.id);
          const base64Data = photoData.data;

          // 检查base64数据是否已有前缀
          if (base64Data.startsWith("data:image/")) {
            return base64Data;
          } else {
            return `data:image/png;base64,${base64Data}`;
          }
        }

        // 情况2: 后端已经返回完整的data URL
        if (
          typeof photoData === "string" &&
          photoData.startsWith("data:image/")
        ) {
          console.log(`第${index + 1}张图片已是完整data URL格式`);
          return photoData;
        }

        // 情况3: 纯base64字符串，需要添加前缀
        if (
          typeof photoData === "string" &&
          !photoData.startsWith("data:") &&
          !photoData.startsWith("http")
        ) {
          console.log(`第${index + 1}张图片是纯base64字符串，添加前缀`);
          // 根据数据特征判断图片类型，默认使用png
          const imageType = photoData.startsWith("/9j/") ? "jpeg" : "png";
          return `data:image/${imageType};base64,${photoData}`;
        }

        // 情况4: HTTP URL
        if (
          typeof photoData === "string" &&
          (photoData.startsWith("http://") || photoData.startsWith("https://"))
        ) {
          console.log(`第${index + 1}张图片是HTTP URL`);
          return photoData;
        }

        // 情况5: 二进制数据转换
        if (photoData instanceof ArrayBuffer) {
          console.log(`第${index + 1}张图片从ArrayBuffer转换`);
          const base64String = arrayBufferToBase64(photoData);
          return `data:image/png;base64,${base64String}`;
        }

        // 情况6: TypedArray
        if (photoData.buffer) {
          console.log(`第${index + 1}张图片从TypedArray转换`);
          const base64String = arrayBufferToBase64(photoData.buffer);
          return `data:image/png;base64,${base64String}`;
        }

        console.warn(
          `第${index + 1}张图片格式未知:`,
          typeof photoData,
          photoData
        );
        return null;
      } catch (e) {
        console.error(`处理第${index + 1}张图片失败:`, e);
        return null;
      }
    })
    .filter(Boolean); // 过滤掉null值
}

// 将后端返回的记录数据恢复到本地存储
function loadPreviousRecords(recordsData) {
  if (typeof window === "undefined") return;

  if (!window.recordUpdateStorage) {
    window.recordUpdateStorage = {};
  }

  console.log("=== 开始恢复暂存记录到本地存储 ===");

  // 获取当前项目和站点信息
  const currentProjectId = selectedProjectId.value;
  const currentSiteId = selectedSiteTaskId.value;

  console.log(
    `当前选中 - 项目ID(selectedProjectId): ${currentProjectId}, 站点ID(selectedSiteTaskId): ${currentSiteId}`
  );

  recordsData.forEach((record) => {
    // 检查记录是否属于当前项目和站点
    // 后端返回的MIS_id对应selectedProjectId，task_id对应selectedSiteTaskId
    const recordProjectId = record.MIS_id;
    const recordSiteId = record.task_id;

    console.log(
      `后端记录 - MIS_id: ${recordProjectId}, task_id: ${recordSiteId}`
    );

    // 只有当项目和站点都匹配时才恢复记录
    // if (recordProjectId != currentProjectId || recordSiteId != currentSiteId) {
    //   console.log(`跳过不匹配的记录: MIS_id=${recordProjectId}, task_id=${recordSiteId} (当前: ${currentProjectId}, ${currentSiteId})`);
    //   return; // 跳过这条记录
    // }

    console.log(
      `记录匹配当前项目站点，开始恢复: MIS_id=${recordProjectId}, task_id=${recordSiteId}`
    );

    // acc_name是行ID，type是表格类型
    const rowId = record.acc_name; // 行ID，如"1", "2", "3"
    const tableType = record.type; // 表格类型，如"usage", "machine", "jg"等

    // 构建记录键：行ID_表格类型，这样可以唯一标识每一行
    const recordKey = `${recordProjectId}_${recordSiteId}_${rowId}_${tableType}`;

    // 将后端数据转换为RecordUpdateModal期望的格式
    const recordData = {
      updatedValue: record.right_value || record.updated_value || "", // 使用right_value作为更新值
      imageList: (record.photo_path || []).map((photoUrl) => {
        console.log("转换图片数据到imageList格式:", photoUrl);
        return {
          url: photoUrl,
          file: null, // 从后端恢复的图片没有file对象
        };
      }),
      accProblem: record.acc_problem || "",
      timestamp: Date.now(),
      // 同时保存后端字段名，确保兼容性
      right_value: record.right_value || record.updated_value || "",
      acc_problem: record.acc_problem || "",
      photo_path: record.photo_path || [],
      // 保存原始数据用于调试
      originalData: {
        MIS_id: record.MIS_id,
        task_id: record.task_id,
        wrong_value: record.wrong_value,
        right_value: record.right_value,
        acc_problem: record.acc_problem,
        photo_path: record.photo_path,
        rowId: rowId,
        tableType: tableType,
      },
    };

    // 保存到全局存储
    window.recordUpdateStorage[recordKey] = recordData;

    console.log("恢复记录到本地存储:", recordKey, recordData);

    // 修复：只有已提交成功的记录才应该显示绿色高亮
    // 检查记录是否已经提交成功（可以通过某个字段判断，比如status或者其他标识）
    // 这里暂时不添加到已修改列表，让用户重新提交后才显示高亮
    // 如果后端有提交状态字段，可以根据该字段判断是否添加高亮
    if (record.status === "submitted" || record.isSubmitted) {
      // 只有明确标记为已提交的记录才显示高亮
      if (!modifiedRecords.value.includes(recordKey)) {
        modifiedRecords.value.push(recordKey);
        console.log("恢复已提交记录的高亮状态:", recordKey);
      }
    } else {
      console.log("记录未提交，不显示高亮:", recordKey);
    }
  });

  console.log("=== 暂存记录恢复完成 ===");
  console.log("已修改记录列表:", modifiedRecords.value);
  console.log("全局存储内容:", window.recordUpdateStorage);

  // 数据已经保存到全局存储中，RecordUpdateModal会在打开时自动加载
  console.log("暂存数据已保存到全局存储，等待模态框打开时加载");
}

function fetchProjectAndSiteData() {
  uni.request({
    url: "./api/projects",
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      console.log("API返回的原始数据:", res.data);
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        fullProjectData.value = res.data;
        console.log("fullProjectData设置为:", fullProjectData.value);

        // 去重
        const seen = new Set();
        projectList.value = res.data
          .filter((item) => {
            if (!seen.has(item.misCode)) {
              seen.add(item.misCode);
              return true;
            }
            return false;
          })
          .map((item) => ({
            misCode: item.misCode,
            projectName: item.projectName,
          }));
        console.log("处理后的projectList:", projectList.value);
      } else {
        console.error("API返回格式错误:", res);
        uni.showToast({ title: "加载项目失败", icon: "none" });
      }
    },
    fail: (error) => {
      console.error("网络请求失败:", error);
      uni.showToast({ title: "网络异常，无法加载项目", icon: "none" });
    },
  });
}

// 选中项目
function onProjectChange(e) {
  const idx = e.detail.value;
  const project = projectList.value[idx] || null;
  if (project) {
    selectedProjectId.value = project.misCode;
    selectedProjectName.value = project.projectName;
    // 设置全局变量供子组件使用
    if (typeof window !== "undefined") {
      window.currentProjectId = project.misCode;
    }
  } else {
    selectedProjectId.value = null;
    selectedProjectName.value = "";
    if (typeof window !== "undefined") {
      window.currentProjectId = null;
    }
  }

  // 重置站点数据
  resetSiteData();

  // 清除已修改记录列表（因为切换了项目）
  modifiedRecords.value = [];

  // 更新站点列表
  updateSiteList();
}

// 选中站点
function onSiteChange(e) {
  const idx = e.detail.value;
  const site = siteList.value[idx] || null;
  if (site) {
    selectedSiteTaskId.value = site.subtaskId;
    selectedSiteName.value = site.siteName;
    window.currentSiteId = site.subtaskId;
  } else {
    selectedSiteTaskId.value = null;
    selectedSiteName.value = "";
  }

  // 重置数据
  resetAllData();

  // 加载数据
  loadAllTabData();
}

function fetchMachineUsage(misId, taskId) {
  uni.request({
    url: `./api/table3y?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        machineUsageList.value = res.data;
      } else {
        uni.showToast({ title: "加载机器使用费数据失败", icon: "none" });
      }
    },
    fail: () => {
      uni.showToast({
        title: "网络异常，无法加载机器使用费数据",
        icon: "none",
      });
    },
  });
}

function fetchInstrumentUsage(misId, taskId) {
  uni.request({
    url: `./api/table3b?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        instrumentUsageList.value = res.data;
      } else {
        uni.showToast({ title: "加载仪器使用费数据失败", icon: "none" });
      }
    },
    fail: () => {
      uni.showToast({
        title: "网络异常，无法加载仪器使用费数据",
        icon: "none",
      });
    },
  });
}

function fetchUsageList(misId, taskId) {
  uni.request({
    url: `./api/usageList?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        usageList.value = res.data;
      } else {
        uni.showToast({ title: "加载用量清单失败", icon: "none" });
      }
    },
    fail: () => {
      uni.showToast({ title: "网络异常，无法加载用量清单", icon: "none" });
    },
  });
}

function fetchSupplierAMaterials(misId, taskId) {
  uni.request({
    url: `./api/jgmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        supplierAMaterials.value = res.data;
      } else {
        console.error("获取甲供材料数据失败：", res);
        supplierAMaterials.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（supplierAMaterials）：", err);
      supplierAMaterials.value = [];
    },
  });
}

function fetchSupplierBMaterials(misId, taskId) {
  uni.request({
    url: `./api/ygmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        supplierBMaterials.value = res.data;
      } else {
        console.error("获取乙供材料数据失败：", res);
        supplierBMaterials.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（supplierBMaterials）：", err);
      supplierBMaterials.value = [];
    },
  });
}

function fetchOtherMaterials(misId, taskId) {
  uni.request({
    url: `./api/othermat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        otherMaterialsList.value = res.data;
      } else {
        console.error("获取其他材料数据失败：", res);
        otherMaterialsList.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（otherMaterials）：", err);
      otherMaterialsList.value = [];
    },
  });
}

function selectTab(key) {
  selectedTab.value = key;
}

function onHistoryReport() {
  // 清除所有暂存记录
  if (pendingChanges.value.length === 0) {
    uni.showToast({ title: "没有暂存记录需要清除", icon: "none" });
    return;
  }

  uni.showModal({
    title: "确认清除",
    content: `确定要清除所有 ${pendingChanges.value.length} 条暂存记录吗？此操作不可恢复。`,
    success: (res) => {
      if (res.confirm) {
        // 清空暂存的修改记录
        pendingChanges.value = [];

        // 清除本地存储的记录（如果有的话）
        try {
          if (typeof window !== "undefined" && window.recordUpdateStorage) {
            window.recordUpdateStorage = {};
          }
        } catch (e) {
          // console.log('清除本地存储失败:', e);
        }

        uni.showToast({
          title: "已清除所有暂存记录",
          icon: "success",
        });
      }
    },
  });
}

function openReportModal() {
  const submitRecordId = props.taskId;

  if (!submitRecordId) {
    uni.showToast({ title: "缺少任务ID，无法提交", icon: "none" });
    return;
  }

  // 直接调用新的提交接口
  uni.showModal({
    title: "确认提交",
    content: "确认要提交所有更改吗？",
    confirmText: "确认提交",
    cancelText: "取消",
    success: (res) => {
      if (res.confirm) {
        submitAllChangesToCheck();
      }
    },
  });
}

// 新的提交所有更改函数
function submitAllChangesToCheck() {
  uni.showLoading({ title: "提交中..." });

  const submitRecordId = props.taskId;

  console.log("提交所有更改的recordID:", submitRecordId);

  if (!submitRecordId) {
    uni.hideLoading();
    uni.showToast({ title: "缺少任务ID，无法提交", icon: "none" });
    return;
  }

  uni.request({
    url: "./api/updateCheck",
    method: "POST",
    header: {
      Authorization: `Bearer ${ui.token}`,
    },
    data: {
      recordID: submitRecordId,
    },
    success: (res) => {
      uni.hideLoading();
      if (res.statusCode === 200) {
        uni.showToast({ title: "提交成功", icon: "success" });
        // 清空暂存记录
        pendingChanges.value = [];
        // 刷新数据
        refreshCurrentTabData();
      } else {
        uni.showToast({ title: "提交失败", icon: "none" });
      }
    },
    fail: (error) => {
      uni.hideLoading();
      console.error("提交失败:", error);
      uni.showToast({ title: "网络错误", icon: "none" });
    },
  });
}

function handleReportMaskClick(e) {
  if (e.target === e.currentTarget) {
    closeReportModal();
  }
}

function closeReportModal() {
  isReportModalOpen.value = false;
}

function closeHistoryModal() {
  isHistoryModalOpen.value = false;
}

async function handleFormSubmit(formData) {
  if (!currentProjectInfo.value) {
    uni.showToast({ title: "项目信息缺失", icon: "none" });
    return;
  }
  uni.showToast({ title: "提交成功", icon: "success" });
  closeReportModal();
}

const currentProjectInfo = computed(() => {
  if (!selectedProjectId.value || !selectedSiteTaskId.value) {
    return null;
  }
  const project = fullProjectData.value.find(
    (item) => item.misCode === selectedProjectId.value
  );
  const task = fullProjectData.value.find(
    (item) => item.subtaskId === selectedSiteTaskId.value
  );
  return project && task
    ? {
        MIS_id: project.misCode,
        project_name: project.projectName,
        task_id: task.subtaskId,
        task_name: task.siteName,
      }
    : null;
});

// 处理行双击事件 - 优化版本，只在提交成功后才触发高亮
function handleRowDoubleClick(item, type, rowIndex) {
  console.log("=== 双击行事件 ===");
  console.log("行数据:", item);
  console.log("表格类型:", type);
  console.log("行索引:", rowIndex);

  // 如果没有传递rowIndex，尝试从当前表格数据中找到索引
  if (rowIndex === undefined || rowIndex === null) {
    console.log("未传递行索引，尝试自动查找...");

    let currentList = [];
    switch (type) {
      case "usage":
        currentList = usageList.value;
        break;
      case "machine":
        currentList = machineUsageList.value;
        break;
      case "instrument":
        currentList = instrumentUsageList.value;
        break;
      case "jg":
        currentList = supplierAMaterials.value;
        break;
      case "yg":
        currentList = supplierBMaterials.value;
        break;
      case "other":
        currentList = otherMaterialsList.value;
        break;
    }

    // 尝试通过数据匹配找到索引
    rowIndex = currentList.findIndex((listItem) => {
      // 比较多个可能的唯一标识符
      return (
        (listItem.id && listItem.id === item.id) ||
        (listItem.de_id && listItem.de_id === item.de_id) ||
        (listItem.name && listItem.name === item.name) ||
        JSON.stringify(listItem) === JSON.stringify(item)
      );
    });

    console.log("自动查找到的行索引:", rowIndex);
  }

  // 根据不同类型的表格，设置当前记录的值
  let currentValue = "";

  //   // 使用行索引+1作为行ID（因为通常行号从1开始）
  //   const rowId = String((rowIndex !== -1 && rowIndex !== undefined) ? rowIndex + 1 : 1);

  //   console.log("计算的行ID:", rowId);

  switch (type) {
    case "usage":
      currentValue = item.standUsage || item.count || "";
      break;
    case "machine":
      currentValue = item.count || item.standUsage || "";
      break;
    case "instrument":
      currentValue = item.count || item.standUsage || "";
      break;
    case "jg":
      currentValue = item.mat_count || item.count || "";
      break;
    case "yg":
      currentValue = item.mat_count || item.count || "";
      break;
    case "other":
      currentValue = item.count || item.standUsage || "";
      break;
    default:
      currentValue = "";
  }

  console.log("当前值:", currentValue);

  // 检查是否有暂存的修改记录，并验证项目站点匹配
  const recordKey = `${selectedProjectId}_${selectedSiteTaskId}_${item.id}_${type}`;
  let existingRecord = null;

  if (
    typeof window !== "undefined" &&
    window.recordUpdateStorage &&
    window.recordUpdateStorage[recordKey]
  ) {
    const storedRecord = window.recordUpdateStorage[recordKey];

    console.log("匹配到的记录:", storedRecord);
    existingRecord = storedRecord;
  }

  // 设置当前记录，保存完整的行数据
  currentRecord.value = {
    id: item.id || item.de_id || item.ID || item.De_id, // 添加记录ID
    misCode: selectedProjectId.value,
    siteTaskId: selectedSiteTaskId.value,
    rowId: item.id, // 使用行ID
    currentValue: currentValue,
    type: type,
    rowData: item, // 保存完整的行数据
    rowIndex: rowIndex, // 保存行索引
    // 如果有暂存记录，直接传递后端字段名
    right_value: existingRecord
      ? existingRecord.right_value || existingRecord.updatedValue
      : "",
    acc_problem: existingRecord
      ? existingRecord.acc_problem || existingRecord.accProblem
      : "",
    photo_path: existingRecord
      ? existingRecord.photo_path || existingRecord.imageList
      : [],
    // 同时保持兼容性
    updatedValue: existingRecord
      ? existingRecord.updatedValue || existingRecord.right_value
      : "",
    accProblem: existingRecord
      ? existingRecord.accProblem || existingRecord.acc_problem
      : "",
    imageList: existingRecord
      ? existingRecord.imageList || existingRecord.photo_path
      : [],
    existingRecord: existingRecord,
  };

  console.log("设置当前记录:", currentRecord.value);
  console.log("预填充数据:", {
    updatedValue: currentRecord.value.updatedValue,
    accProblem: currentRecord.value.accProblem,
    imageCount: currentRecord.value.imageList?.length || 0,
  });

  // 显示模态框
  isUpdateModalVisible.value = true;
}

// 关闭记录更新模态框
function closeUpdateModal() {
  isUpdateModalVisible.value = false;
}

// 处理记录更新提交（直接提交到后端）
function handleUpdateSubmit(formData) {
  console.log("收到更新提交:", formData);

  // 验证记录ID，支持多种ID来源
  let recordId = formData.id;

  // 如果formData.id无效，尝试从rowData中获取
  if (!recordId || recordId === "-") {
    if (formData.rowData) {
      recordId =
        formData.rowData.id ||
        formData.rowData.de_id ||
        formData.rowData.ID ||
        formData.rowData.De_id;
    }
  }

  // 如果还是没有有效ID，检查是否为不修改直接提交
  if (!recordId || recordId === "-") {
    if (formData.id === "-") {
      // 处理不修改直接提交的情况
      submitNoModificationRecord(formData, (result) => {
        if (result.success) {
          closeUpdateModal();
        }
      });
      return;
    } else {
      console.error("无法获取有效的记录ID:", formData);
      uni.showToast({
        title: "记录ID无效，无法提交",
        icon: "none",
      });
      return;
    }
  }

  // 更新formData中的ID
  formData.id = recordId;
  console.log("使用的记录ID:", recordId);

  // 先保存到暂存记录（用于关闭模态框后重新打开时恢复数据）
  saveToTempStorage(formData);

  // 获取当前位置信息
  uni.showLoading({ title: "获取位置信息..." });

  uni.getLocation({
    type: "wgs84",
    success: (res) => {
      currentLocation.value = {
        lat: res.latitude,
        lon: res.longitude,
      };

      // 直接提交单条记录
      submitSingleRecord(formData);
    },
    fail: (err) => {
      console.error("获取位置失败:", err);
      uni.showToast({
        title: "获取位置失败，将使用缓存位置提交",
        icon: "none",
      });

      // 即使位置获取失败也继续提交
      submitSingleRecord(formData);
    },
  });
}

// 提交单条记录到后端
function submitSingleRecord(formData) {
  console.log(1);
  uni.showLoading({ title: "提交中..." });
  console.log(2);
  // 使用props.taskId作为记录ID，确保不为undefined
  const submitRecordId =
    props.taskId || `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

  console.log("提交的recordID:", submitRecordId);
  console.log("props.taskId:", props.taskId);

  // 获取真实的行ID
  const getRealRowId = (formData) => {
    const rowData = formData.rowData;
    if (rowData) {
      return (
        rowData.id ||
        rowData.de_id ||
        rowData.ID ||
        rowData.De_id ||
        rowData.record_id ||
        rowData.recordId ||
        formData.id
      );
    }
    return formData.id;
  };

  const realRowId = getRealRowId(formData);

  // 准备提交数据
  const submitData = {
    projectId: selectedProjectId.value,
    siteId: selectedSiteTaskId.value,
    recordId: submitRecordId,
    type: formData.type,
    currentValue: formData.currentValue,
    updatedValue: formData.updatedValue,
    accProblem: formData.accProblem || "",
    timestamp: Date.now(),
    lat: currentLocation.value.lat,
    lon: currentLocation.value.lon,
    rowId: realRowId,
  };

  // 检查是否有图片需要上传
  const imageFiles = formData.imageFiles || [];

  if (imageFiles.length > 0) {
    // 有图片，使用文件上传
    submitUpdateWithImages(imageFiles, submitData, (result) => {
      uni.hideLoading();
      if (result.success) {
        uni.showToast({ title: "提交成功", icon: "success" });

        // 优化：只有在真正提交成功后才添加到已修改列表，触发绿色高亮
        const recordKey = `${selectedProjectId.value}_${selectedSiteTaskId.value}_${realRowId}_${formData.type}`;
        if (!modifiedRecords.value.includes(recordKey)) {
          modifiedRecords.value.push(recordKey);
          console.log(
            "提交成功，添加到已修改记录列表（触发绿色高亮）:",
            recordKey
          );
        }

        // 提交成功后，更新全局存储中的数据状态
        if (
          typeof window !== "undefined" &&
          window.recordUpdateStorage &&
          window.recordUpdateStorage[recordKey]
        ) {
          window.recordUpdateStorage[recordKey] = {
            ...window.recordUpdateStorage[recordKey],
            isSubmitted: true,
            submitTime: Date.now(),
            submitStatus: "success",
          };
          console.log("更新全局存储提交状态（含图片）:", recordKey);
        }

        closeUpdateModal();
        refreshCurrentTabData();
      } else {
        uni.showToast({ title: "提交失败", icon: "none" });
      }
    });
  } else {
    // 无图片，直接POST提交
    uni.request({
      url: "./api/updateRecord",
      method: "POST",
      header: {
        Authorization: `Bearer ${ui.token}`,
        "Content-Type": "application/json",
      },
      data: {
        ...submitData,
        photo_path: "-",
      },
      success: (res) => {
        uni.hideLoading();
        if (res.statusCode === 200) {
          uni.showToast({ title: "提交成功", icon: "success" });

          // 优化：只有在真正提交成功后才添加到已修改列表，触发绿色高亮
          const recordKey = `${selectedProjectId.value}_${selectedSiteTaskId.value}_${realRowId}_${formData.type}`;
          if (!modifiedRecords.value.includes(recordKey)) {
            modifiedRecords.value.push(recordKey);
            console.log(
              "提交成功，添加到已修改记录列表（触发绿色高亮）:",
              recordKey
            );
          }

          // 提交成功后，更新全局存储中的数据状态
          if (
            typeof window !== "undefined" &&
            window.recordUpdateStorage &&
            window.recordUpdateStorage[recordKey]
          ) {
            window.recordUpdateStorage[recordKey] = {
              ...window.recordUpdateStorage[recordKey],
              isSubmitted: true,
              submitTime: Date.now(),
              submitStatus: "success",
            };
            console.log("更新全局存储提交状态:", recordKey);
          }

          closeUpdateModal();
          refreshCurrentTabData();
        } else {
          uni.showToast({ title: "提交失败", icon: "none" });
        }
      },
      fail: (error) => {
        uni.hideLoading();
        console.error("提交失败:", error);
        uni.showToast({ title: "网络错误", icon: "none" });
      },
    });
  }
}

// 根据当前选中的标签刷新数据
function refreshCurrentTabData() {
  if (!selectedProjectId.value || !selectedSiteTaskId.value) return;

  const misId = selectedProjectId.value;
  const taskId = selectedSiteTaskId.value;

  switch (selectedTab.value) {
    case "usage":
      fetchUsageList(misId, taskId);
      break;
    case "machine":
      fetchMachineUsage(misId, taskId);
      break;
    case "instrument":
      fetchInstrumentUsage(misId, taskId);
      break;
    case "jg":
      fetchSupplierAMaterials(misId, taskId);
      break;
    case "yg":
      fetchSupplierBMaterials(misId, taskId);
      break;
    case "other":
      fetchOtherMaterials(misId, taskId);
      break;
  }
}

// 提交更新记录和图片 - 使用files参数支持多图片上传
function submitUpdateWithImages(imageFiles, formData, callback) {
  console.log("开始上传多张图片:", imageFiles);
  console.log("表单数据:", formData);

  // 检查图片文件是否有效
  if (!imageFiles || imageFiles.length === 0) {
    console.error("没有图片文件");
    callback({ success: false, error: "没有图片文件" });
    return;
  }

  // 验证每个图片文件对象
  const validImageFiles = imageFiles.filter((file) => {
    if (!file) {
      console.warn("发现空的图片文件对象");
      return false;
    }

    // 检查是否有有效的路径信息
    const hasPath = file.path || file.tempFilePath || file.url;
    if (!hasPath) {
      console.warn("图片文件缺少路径信息:", file);
      return false;
    }

    return true;
  });

  if (validImageFiles.length === 0) {
    console.error("没有有效的图片文件对象");
    callback({ success: false, error: "没有有效的图片文件" });
    return;
  }

  // 准备files数组，用于多文件上传
  const files = validImageFiles
    .map((imageFile, index) => {
      console.log(`处理第${index + 1}张图片文件:`, imageFile);

      // 支持多种文件路径格式：path、tempFilePath、url（用于暂存数据恢复）
      const filePath =
        imageFile.path || imageFile.tempFilePath || imageFile.url;
      if (!filePath) {
        console.error(`第${index + 1}张图片路径无效:`, imageFile);
        return null;
      }

      console.log(`第${index + 1}张图片路径:`, filePath);

      return {
        name: `image${index}`, // 每个文件使用不同的字段名
        uri: filePath,
      };
    })
    .filter((file) => file !== null); // 过滤掉无效的文件

  if (files.length === 0) {
    console.error("没有有效的图片文件");
    console.error("原始imageFiles:", imageFiles);
    console.error("验证后的validImageFiles:", validImageFiles);
    callback({ success: false, error: "没有有效的图片文件" });
    return;
  }

  console.log("准备上传的文件数组:", files);

  // 使用uni.uploadFile的files参数一次性上传多个文件
  uni.uploadFile({
    url: "./api/updateRecord",
    files: files, // 使用files参数上传多个文件
    header: {
      Authorization: `Bearer ${ui.token}`,
      // 不设置 Content-Type，让 uni.uploadFile 自动处理
    },
    formData: {
      ...formData,
      imageCount: files.length.toString(), // 告诉服务器图片总数
    },
    timeout: 30000,
    success: (res) => {
      // console.log("多图片上传成功:", res);
      handleUploadResponse(res, callback);
    },
    fail: (error) => {
      console.error("多图片上传失败:", error);
      handleUploadError(error, callback);
    },
  });
}

// 处理上传响应的通用函数
function handleUploadResponse(res, callback) {
  // console.log("上传响应:", res);
  // console.log("响应状态码:", res.statusCode);
  // console.log("响应数据:", res.data);

  if (res.statusCode === 200) {
    let result;
    try {
      result = JSON.parse(res.data);
    } catch (e) {
      console.error("解析响应数据失败:", res.data);
      callback({ success: true, data: { message: "上传成功" } });
      return;
    }

    if (result && result.success) {
      callback({ success: true, data: result });
    } else if (result && result.code === 200) {
      callback({ success: true, data: result });
    } else {
      console.error("上传失败:", result);
      callback({ success: false, error: result });
    }
  } else {
    console.error("上传HTTP错误:", res.statusCode, res.data);
    callback({ success: false, error: `HTTP ${res.statusCode}: ${res.data}` });
  }
}

// 处理不修改直接提交的记录
function submitNoModificationRecord(formData, callback) {
  // console.log("提交不修改记录:", formData);

  uni.request({
    url: "./api/updateRecord",
    method: "POST",
    header: {
      Authorization: `Bearer ${ui.token}`,
      "Content-Type": "application/json",
    },
    data: formData,
    timeout: 30000,
    success: (res) => {
      // console.log("不修改记录提交成功:", res);
      handleUploadResponse(res, callback);
    },
    fail: (error) => {
      console.error("不修改记录提交失败:", error);
      handleUploadError(error, callback);
    },
  });
}

// 处理上传错误的通用函数
function handleUploadError(error, callback) {
  console.error("上传网络错误:", error);
  console.error("错误详情:", JSON.stringify(error));

  let errorMsg = "网络请求失败";
  if (error.errMsg) {
    if (error.errMsg.includes("timeout")) {
      errorMsg = "请求超时，请检查网络连接";
    } else if (error.errMsg.includes("fail")) {
      errorMsg = "请求失败，请检查服务器地址和网络连接";
    } else {
      errorMsg = error.errMsg;
    }
  }

  callback({ success: false, error: errorMsg });
}

// 保存到暂存存储（用于关闭模态框后重新打开时恢复数据）
function saveToTempStorage(formData) {
  if (typeof window === "undefined") return;

  if (!window.recordUpdateStorage) {
    window.recordUpdateStorage = {};
  }

  // 构建记录键
  const recordKey = `${selectedProjectId.value}_${selectedSiteTaskId.value}_${formData.id}_${formData.type}`;

  // 处理图片数据，确保格式统一
  const processedImageList = (formData.imageList || [])
    .map((img) => {
      if (typeof img === "string") {
        return {
          url: img,
          file: null,
          originalPath: img,
          isNewUpload: false,
          timestamp: Date.now(),
        };
      } else if (img && typeof img === "object") {
        return {
          url: img.url || img.data || img,
          file: img.file || null,
          originalPath: img.originalPath || img.url || img.data || img,
          isNewUpload: img.isNewUpload || false,
          id: img.id || null,
          timestamp: img.timestamp || Date.now(),
        };
      }
      return null;
    })
    .filter(Boolean);

  // 保存记录数据
  const recordData = {
    updatedValue: formData.updatedValue || "",
    imageList: processedImageList,
    accProblem: formData.accProblem || "",
    timestamp: Date.now(),
    // 保持后端字段名兼容性
    right_value: formData.updatedValue || "",
    acc_problem: formData.accProblem || "",
    photo_path: processedImageList,
    // 保存原始数据用于调试
    originalData: {
      MIS_id: selectedProjectId.value,
      task_id: selectedSiteTaskId.value,
      wrong_value: formData.currentValue,
      right_value: formData.updatedValue,
      acc_problem: formData.accProblem,
      photo_path: processedImageList,
      rowId: formData.id,
      tableType: formData.type,
    },
  };

  // 保存到全局存储
  window.recordUpdateStorage[recordKey] = recordData;

  console.log("保存暂存记录:", recordKey);
  console.log("保存的图片数量:", processedImageList.length);

  // 修复：暂存记录不应该触发绿色高亮，只有提交成功后才显示高亮
  // 移除这里的高亮逻辑，让高亮只在提交成功后触发
  console.log("暂存记录已保存，等待用户提交后才显示高亮");
}
</script>

<style scoped>
.container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 80px;
  /* 底部按钮高度 */
  box-sizing: border-box;
  position: relative;
}

/* 筛选区域 */
.filter-area {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-label {
  font-size: 15px;
  color: #333;
  margin-bottom: 6px;
  white-space: nowrap;
}

.picker {
  height: 40px;
  line-height: 40px;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  border: 1px solid #e9ecef;
  transition: border-color 0.2s ease;
}

.picker:active {
  border-color: #409eff;
}

/* 语音输入行 */
.voice-row {
  margin-top: 12px;
}

/* 现代化搜索组件样式 */
.modern-search-container {
  margin-top: 16px;
  padding: 0 4px;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 4px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.08),
    inset 0 1px 2px rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

.search-wrapper:focus-within {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(64, 158, 255, 0.15),
    0 4px 16px rgba(64, 158, 255, 0.1), inset 0 1px 2px rgba(255, 255, 255, 0.6);
  border-color: rgba(64, 158, 255, 0.3);
}

.modern-search-input {
  flex: 1;
  height: 48px;
  padding: 0 20px;
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  background: transparent;
  border: none;
  outline: none;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.modern-search-input::placeholder {
  color: #666;
  font-weight: 400;
  font-size: 15px;
}

.modern-search-input:focus {
  background: rgba(64, 158, 255, 0.05);
}

.modern-search-btn {
  height: 48px;
  padding: 0 20px;
  font-size: 15px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(135deg, #409eff 0%, #409eff 100%);
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4),
    inset 0 1px 2px rgba(255, 255, 255, 0.3);
  position: relative;
  overflow: hidden;
}

.modern-search-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.3),
    transparent
  );
  transition: left 0.6s ease;
}

.modern-search-btn:hover::before {
  left: 100%;
}

.modern-search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5),
    inset 0 1px 2px rgba(255, 255, 255, 0.4);
}

.modern-search-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3),
    inset 0 1px 2px rgba(255, 255, 255, 0.2);
}

.search-icon {
  font-size: 16px;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2));
}

.search-text {
  position: relative;
  z-index: 1;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .modern-search-input {
    font-size: 16px;
    padding: 0 16px;
  }

  .modern-search-btn {
    padding: 0 16px;
  }

  .search-text {
    display: none;
  }
}

/* 标签栏 */
.tab-bar {
  flex-direction: row;
  display: flex;
  justify-content: space-around;
  margin-top: 12px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  padding: 10px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
  border-right: 1px solid #f0f0f0;
}

.tab-item:last-child {
  border-right: none;
}

.tab-item.active-tab {
  background-color: #409eff;
  color: #fff;
}

.tab-item.active-tab text {
  color: #fff;
}

/* 空提示 */
.empty-message {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 暂存修改提示 */
.pending-changes-tip {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  margin-bottom: 20px;
}

.tip-icon {
  font-size: 16px;
  margin-right: 8px;
}

.tip-text {
  font-size: 14px;
  color: #856404;
  flex: 1;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: space-between;
  z-index: 9999;
  box-sizing: border-box;
}

.action-btn {
  flex: 1;
  height: 50px;
  border-radius: 25px;
  margin: 0 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-btn:active {
  transform: scale(0.98);
}

.history-btn {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e6eb 100%);
  color: #333;
}

.report-btn {
  background: linear-gradient(135deg, #409eff 0%, #2678d6 100%);
  color: #fff;
  position: relative;
}

.badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  min-width: 16px;
  height: 16px;
  line-height: 12px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 模态框遮罩层（问题上报） */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
}

/* 模态框内容容器（问题上报） */
.modal-container {
  background-color: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 100000;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-close {
  width: 24px;
  height: 24px;
  text-align: center;
  line-height: 24px;
  font-size: 18px;
  color: #999;
}

.close-text {
  font-size: 20px;
  font-weight: bold;
}

.modal-body {
  padding: 20px;
}

/* 修改过的记录绿色边框高亮样式 */
.modified-row {
  border: 2px solid #67c23a !important;
  background-color: #f0f9ff !important;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2) !important;
}
</style>
